import ColorUISdk from '../../mp-sdk/index'

const sdk = new ColorUISdk({
  env: 'dev',
  version: '1.0.0',
  api: {
    dev: { 
      url: 'http://192.168.134.31:5000'
    }
  }
})

Page({
  data: {
    userInfo: null as any,
    checkinCount: 0,
    feedbackCount: 0,
    identifyCount: 0,
    recentFeedback: [] as any[],
    recentCheckins: [] as any[],
    recentIdentifies: [] as any[],
    hasAnyRecords: false
  },

  onShow() {
    this.checkLoginStatus()
  },

  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    const token = wx.getStorageSync('token')
    
    console.log('存储的用户信息:', userInfo)
    
    this.setData({
      userInfo: userInfo && token ? userInfo : null
    })
    
    if (this.data.userInfo) {
      this.loadAllUserData()
    } else {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }
  },

  // 加载所有用户数据
  async loadAllUserData() {
    try {
      await Promise.all([
        this.loadUserStats(),
        this.loadRecentRecords()
      ])
      
      this.checkHasAnyRecords()
    } catch (error) {
      console.error('加载用户数据失败:', error)
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      })
    }
  },

  // 加载用户统计数据 - 修复API路径
  async loadUserStats() {
    const userId = this.data.userInfo?.user_id;
    const token = wx.getStorageSync('token');
    
    if (!userId || !token) {
      console.error('用户ID或token不存在');
      wx.showToast({
        title: '用户信息获取失败，请重新登录',
        icon: 'none'
      })
      return;
    }
    
    try {
      // 使用识别记录API获取统计数据
      const identifyRes = await sdk.request({
        url: `/api/records?page=1&limit=1`, // 使用识别记录API
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (identifyRes.code === 0 && identifyRes.data) {
        this.setData({
          identifyCount: identifyRes.data.total || 0
        })
      } else {
        console.error('获取识别记录统计失败:', identifyRes.msg)
      }
      
      // 尝试获取打卡和反馈统计数据（如果有对应的API）
      try {
        const statsRes = await sdk.request({
          url: `/api/user/stats/${userId}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (statsRes.code === 0) {
          this.setData({
            checkinCount: statsRes.data.checkinCount || 0,
            feedbackCount: statsRes.data.feedbackCount || 0
          })
        }
      } catch (statsError) {
        console.log('获取打卡和反馈统计数据失败，使用默认值')
        // 如果统计API不可用，保持默认值
      }
      
    } catch (error) {
      console.error('加载用户统计数据失败:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    }
  },

  // 加载最近记录 - 修复API路径
  async loadRecentRecords() {
    const userId = this.data.userInfo?.user_id;
    const token = wx.getStorageSync('token');
    
    if (!userId || !token) {
      console.error('用户ID或token不存在');
      return;
    }
    
    try {
      // 使用识别记录API获取最近记录
      const identifyRes = await sdk.request({
        url: `/api/records?page=1&limit=3`, // 使用识别记录API
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      // 尝试获取最近反馈和打卡记录（如果有对应的API）
      let feedbackRes = { code: -1, data: [] };
      let checkinRes = { code: -1, data: [] };
      
      try {
        feedbackRes = await sdk.request({
          url: `/api/user/feedback/recent?limit=3`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
      } catch (e) {
        console.log('获取最近反馈记录失败');
      }
      
      try {
        checkinRes = await sdk.request({
          url: `/api/user/checkin/recent?limit=3`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
      } catch (e) {
        console.log('获取最近打卡记录失败');
      }
      
      this.setData({
        recentFeedback: feedbackRes.code === 0 ? feedbackRes.data : [],
        recentCheckins: checkinRes.code === 0 ? checkinRes.data : [],
        recentIdentifies: identifyRes.code === 0 ? identifyRes.data.records || [] : []
      });
    } catch (error) {
      console.error('加载最近记录失败:', error);
    }
  },

  // 检查是否有任何记录
  checkHasAnyRecords() {
    const { recentFeedback, recentCheckins, recentIdentifies } = this.data
    this.setData({
      hasAnyRecords: recentFeedback.length > 0 || 
                    recentCheckins.length > 0 || 
                    recentIdentifies.length > 0
    })
  },

  // 格式化时间
  formatTime(timeString: string) {
    if (!timeString) return ''
    
    const date = new Date(timeString)
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
    
    if (diffDays === 0) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    } else if (diffDays === 1) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    } else if (diffDays < 7) {
      return `${diffDays}天前`
    } else {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }
  },

  // 前往登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('userInfo')
          wx.removeStorageSync('token')
          
          this.setData({
            userInfo: null,
            checkinCount: 0,
            feedbackCount: 0,
            identifyCount: 0,
            recentFeedback: [],
            recentCheckins: [],
            recentIdentifies: [],
            hasAnyRecords: false
          })
          
          wx.showToast({
            title: '已退出登录',
            icon: 'none'
          })
        }
      }
    })
  },

  // 导航到打卡历史
  goToCheckinHistory() {
    wx.navigateTo({
      url: '/pages/checkin-history/checkin-history'
    })
  },

  // 导航到反馈历史
  goToFeedbackHistory() {
    wx.navigateTo({
      url: '/pages/feedback-history/feedback-history'
    })
  },

  // 导航到识别历史
  goToIdentifyHistory() {
    wx.navigateTo({
      url: '/pages/identify-history/identify-history'
    })
  },

  // 导航到所有记录
  goToAllRecords() {
    wx.navigateTo({
      url: '/pages/all-records/all-records'
    })
  },

  // 导航到提交反馈
  goToFeedback() {
    wx.navigateTo({
      url: '/pages/feedback/feedback'
    })
  },

  // 导航到设置页面
  goToSetting() {
    wx.navigateTo({
      url: '/pages/setting/setting'
    })
  },

  // 导航到关于我们
  goToAbout() {
    wx.navigateTo({
      url: '/pages/about/about'
    })
  },

  // 导航到帮助中心
  goToHelp() {
    wx.navigateTo({
      url: '/pages/help/help'
    })
  },

  // 导航到反馈详情
  goToFeedbackDetail(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/feedback-detail/feedback-detail?id=${id}`
    })
  },

  // 导航到打卡详情
  goToCheckinDetail(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/checkin-detail/checkin-detail?id=${id}`
    })
  },

  // 导航到建筑详情
  goToBuildingDetail(e: any) {
    const buildingId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/building-detail/building-detail?id=${buildingId}`
    })
  }
})